#include "userservice.h"
#include "Core/dbcontroler.h"
#include "Core/tcpuserconnect.h"
#include "Core/mytcpserver.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
UserService::UserService(QObject *parent) : QObject(parent)
{
    connect(this,&UserService::ThrowMatchTcpUser,
            MyTcpServer::get_instance().get(),&MyTcpServer::ConnectUserAndTcp);
}

void UserService::_doUserRegister(std::shared_ptr<PDU>recvPDU,TcpUserConnect* UserPtr)
{
    //收
    char* Info=new char[10000000]{'\0'};
    memcpy(Info,(char*)recvPDU.get()+sizeof(PDU),recvPDU->MsgLength);
    QString body=QString(Info);
    delete [] Info;
    Info=nullptr;
    QJsonDocument BodyJsonDoc=QJsonDocument::fromJson(body.toUtf8());
    if(BodyJsonDoc.isNull())return;
    if(!BodyJsonDoc.isObject())return;

    //解
    QJsonObject BodyJson=BodyJsonDoc.object();
    QString UserName=BodyJson["USER"].toString();
    QString UserPwd=BodyJson["PWD"].toString();

    //发
    QJsonObject RInfo;

    //RespondPDU->MessageType=MSG_TYPE_USER_REGISER_RESPOND;
    if(DBControler::get_instance()->_RegisterUser(UserName.toStdString().c_str(),UserPwd.toStdString().c_str())){
        RInfo["REGSAY"]="注册成功";
        RInfo["REGSTATUS"]=1;

    }else{
        RInfo["REGSAY"]="注册失败";
        RInfo["REGSTATUS"]=0;
    }
    UserPtr->SendMsg(MSG_TYPE_USER_REGISER_RESPOND,RInfo);
}

void UserService::_doUserLogin(std::shared_ptr<PDU>recvPDU,TcpUserConnect* UserPtr)
{

    //收
    char* Info=new char[10000000]{'\0'};
    memcpy(Info,(char*)recvPDU.get()+sizeof(PDU),recvPDU->MsgLength);
    QString body=QString(Info);
    delete [] Info;
    Info=nullptr;

    QJsonDocument BodyJsonDoc=QJsonDocument::fromJson(body.toUtf8());
    if(BodyJsonDoc.isNull())return;
    if(!BodyJsonDoc.isObject())return;
    QJsonObject BodyJson=BodyJsonDoc.object();
    QString UserName=BodyJson["USER"].toString();
    QString UserPwd=BodyJson["PWD"].toString();

    UserPtr->setUserName(UserName);
    QMap<QString,QVariant> LoginData;
    DBControler::get_instance()->_LoginUser(UserName.toStdString().c_str(),UserPwd.toStdString().c_str(),LoginData);

    //发
    QJsonObject RInfo;
    RInfo["USER"]=UserName;
    if(LoginData.size()==0){
        RInfo["LOGINSAY"]="LOGIN_FAIL";
        RInfo["LOGINSTATUS"]=0;
        UserPtr->SendMsg(MSG_TYPE_USER_LOGIN_RESPOND,RInfo);
    }else{
        RInfo["LOGINSAY"]="LOGIN_SUCCESS";
        RInfo["LOGINSTATUS"]=1;
        UserPtr->SendMsg(MSG_TYPE_USER_LOGIN_RESPOND,RInfo);
        emit ThrowMatchTcpUser(UserPtr,UserName);
    }
    return;
}

void UserService::_doDownLine(std::shared_ptr<PDU>recvPDU,TcpUserConnect* UserPtr)
{
    QString UserName=recvPDU->caData;
    ////破坏了单一职责原则
    DBControler::get_instance()
            ->_DownloadUpdate(UserName.toUtf8()
                              .toStdString().c_str());

    emit ThrowDownLine(UserPtr,UserName);
}
